<?php
/**
 * @Author: Xu Liu email:2867557054@qq.com
 * @Date:   2016-12-15 13:31:33
 * @Last Modified by:   Xu Liu
 * @Last Modified time: 2018-03-27 22:24:50
 */
if (!defined('IN_DISCUZ')) {
    exit('Access Denied');
}

class IndexContrl extends BaseXf
{
    public function index()
    {
        global $_G;
        if (checkmobile()) {
            dheader('location:' . $_G['siteurl'] . mbreurl('index'));
        }
        $topics   = C::t('#jameson_read#jamesonread_topics')->fetch_books();
        $indexadv = C::t('#jameson_read#jamesonread_topics')->fetch_pc_adv(2);
        $toutiaos = C::t('#jameson_read#jamesonread_topics')->fetch_by_type(5);
        $images   = array();
        foreach (explode('|||', trim($_G['cache']['plugin']['jameson_read']['pchuandengimg'])) as $key => $value) {
            $images[] = explode('###', trim($value));
        }
        $categorys = $this->_tuijian();
        // debug($categorys);
        $paihangbang     = $this->_paihang();
        $nobbname        = true;
        $navtitle        = preg_replace('/\[zhanming\]/i', $_G['setting']['bbname'], C::t('common_setting')->fetch('xf512seo_index'));
        $metadescription = $_G['jameson_read']['seodescr'];
        $metakeywords    = $_G['jameson_read']['seokeywords'];
        $_G['setting']['seohead'] .= '<meta name="renderer"content="webkit" />';
        include template("diy:index_index", 0, './source/plugin/jameson_read/template/' . $_G['jameson_read']['template']);
    }
    public function category()
    {
        global $_G;
        dheader('location:' . trim($_G['siteurl'], "/") . '/' . jamesonurl('shaixuan', 'shaixuan', 'category_id', $_GET['category_id']));
    }
    public function paihang()
    {
        global $_G;
        if (checkmobile()) {
            dheader('location:' . $_G['siteurl'] . mbreurl('paihang'));
        }
        $type        = $_GET['type'] ? daddslashes($_GET['type']) : '';
        $currentpage = $_GET['page'] ? intval($_GET['page']) : 1;
        if (!$type) {
            $paihangbang = $this->_paihang();
        } else {
            $counts = C::t('#jameson_read#jamesonread_books')->count_by_con(array($type == 'sell' ? 'sell' : ''), 1);
            $cururl = 'plugin.php?id=jameson_read&contrl=index&act=paihang&type=' . $type;
            if ($type == 'sell') {
                $books = C::t('#jameson_read#jamesonread_books')->fetchAll_by_field(array('sell'), array(0), array(), ($currentpage - 1) * 30, 30);
            } else {
                $books = C::t('#jameson_read#jamesonread_books')->fetchAll_by_field(array(), array(), array($type . ' DESC ', $type == 'scores' ? ' dpcount asc' : ' addtime DESC'), ($currentpage - 1) * 30, 30);
            }
            $pageshow = multi($counts, 30, $currentpage, $cururl);
        }
        $categorys = $this->_tuijian();
        $adv       = C::t('#jameson_read#jamesonread_topics')->fetch_pc_adv(3, 4);
        $navtitle  = lang('plugin/jameson_read', 'paihangbang');
        $_G['setting']['seohead'] .= '<meta name="renderer"content="webkit" />';
        $metadescription = $_G['jameson_read']['seodescr'];
        $metakeywords    = $_G['jameson_read']['seokeywords'];
        include template("diy:index_paihang", 0, './source/plugin/jameson_read/template/' . $_G['jameson_read']['template']);
    }
    public function shaixuan()
    {
        global $_G;
        if (checkmobile()) {
            dheader('location:' . $_G['siteurl'] . mbreurl('fenlei'));
        }
        $sxdata        = array();
        $shaixuantitle = '';
        if (isset($_GET['category_id']) && $_GET['category_id'] != 'empty') {
            $sxdata['category_id'] = intval($_GET['category_id']) ? intval($_GET['category_id']) : 0;
            $parent_id             = C::t('#jameson_read#jamesonread_categorys')->fetch_pid_byid($sxdata['category_id']);
            $shaixuantitle .= C::t('#jameson_read#jamesonread_categorys')->fetch_name($sxdata['category_id']) . '|';
        }
        if (isset($_GET['is_top']) && $_GET['is_top'] != 'empty') {
            if ($_GET['is_top']) {
                $sxdata['is_top'] = 1;
                $shaixuantitle .= lang('plugin/jameson_read', 'tuijian') . '|';
            } else {
                $shaixuantitle .= lang('plugin/jameson_read', 'weituijian') . '|';
                $sxdata['is_top'] = 0;
            }
        }
        if (isset($_GET['plan']) && $_GET['plan'] != 'empty') {
            if ($_GET['plan']) {
                $sxdata['plan'] = 1;
                $shaixuantitle .= lang('plugin/jameson_read', 'yiwanjie') . '|';
            } else {
                $shaixuantitle .= lang('plugin/jameson_read', 'lianzaizhong') . '|';
                $sxdata['plan'] = 0;
            }
        }
        if (isset($_GET['bookmoney']) && $_GET['bookmoney'] != 'empty') {
            $sxdata['bookmoney'] = intval($_GET['bookmoney']) ? 1 : 0;
            if ($_GET['bookmoney']) {
                $sxdata['bookmoney'] = 1;
                $shaixuantitle .= 'VIP|';
            } else {
                $shaixuantitle .= lang('plugin/jameson_read', 'mianfeibooks') . '|';
                $sxdata['bookmoney'] = 0;
            }
        }
        if (isset($_GET['zishu']) && $_GET['zishu'] != 'empty') {
            $sxdata['zishu'] = intval($_GET['zishu']);
            if ($sxdata['zishu'] < 10000001) {
                $shaixuantitle .= lang('plugin/jameson_read', 'xiaoyu') . $sxdata['zishu'] . lang('plugin/jameson_read', 'zi');
            } else {
                $shaixuantitle .= lang('plugin/jameson_read', 'dayu') . $sxdata['zishu'] . lang('plugin/jameson_read', 'zi');
            }
        }
        $shaixuantitle   = $shaixuantitle ? trim($shaixuantitle, '|') : lang('plugin/jameson_read', 'shaixuan');
        $urlpars         = http_build_query($sxdata);
        $counts          = C::t('#jameson_read#jamesonread_books')->count_shaixuan($sxdata);
        $pagesize        = 30;
        $currentpage     = $_GET['page'] ? intval($_GET['page']) : 1;
        $books           = C::t('#jameson_read#jamesonread_books')->fetch_shaixuan($sxdata, ($currentpage - 1) * $pagesize, $pagesize);
        $pageshow        = multi($counts, $pagesize, $currentpage, 'plugin.php?id=jameson_read&contrl=index&act=shaixuan&' . trim($urlpars, '&'));
        $allcounts       = C::t('#jameson_read#jamesonread_books')->count();
        $adv             = C::t('#jameson_read#jamesonread_topics')->fetch_pc_adv(3, 4);
        $paihangbang     = $this->_paihang();
        $categorys       = $this->_tuijian();
        $nobbname        = true;
        $navtitle        = preg_replace(array('/\[shaixuan\]/i', '/\[zhanming\]/i'), array($shaixuantitle, $_G['setting']['bbname']), C::t('common_setting')->fetch('xf512seo_shaixuan'));
        $metadescription = $_G['jameson_read']['seodescr'];
        $metakeywords    = $_G['jameson_read']['seokeywords'];
        $_G['setting']['seohead'] .= '<meta name="renderer"content="webkit" />';
        include template("diy:index_shaixuan", 0, './source/plugin/jameson_read/template/' . $_G['jameson_read']['template']);
    }
    public function zuozhe()
    {
        global $_G;
        if (checkmobile()) {
            dheader("location:" . trim($_G['siteurl'], "/") . "/plugin.php?id=jameson_read&contrl=touch&act=zuozhe&author=" . $_GET['zuozhe_name']);
        }
        if (!$_GET['zuozhe_name']) {
            showmessage(lang('plugin/jameson_read', 'laiyuanfeifa'));
        }
        $currentpage = $_GET['page'] ? intval($_GET['page']) : 1;
        if ($_GET['zuozhe_name']) {
            $authorname = $_GET['zuozhe_name'];
            $counts     = DB::result_first('SELECT count(*) FROM %t WHERE author=%s', array('jamesonread_books', $authorname));
            $cururl     = './plugin.php?id=jameson_read&contrl=index&act=zuozhe&zuozhe_name=' . $authorname;
            $books      = DB::fetch_all('SELECT b.*,c.category_name FROM %t AS b INNER JOIN %t AS c ON b.category_id=c.category_id WHERE b.author=%s LIMIT %d,%d', array('jamesonread_books', 'jamesonread_categorys', $authorname, 30 * ($currentpage - 1), 30));
        }
        $authorinfo = '';
        foreach ($books as $key => $value) {
            if (!$authorinfo && $value['authorinfo']) {
                $authorinfo = $value['authorinfo'];
            }
        }
        $pageshow        = multi($counts, 30, $currentpage, $cururl);
        $paihangbang     = $this->_paihang();
        $categorys       = $this->_tuijian();
        $adv             = C::t('#jameson_read#jamesonread_topics')->fetch_pc_adv(3, 4);
        $navtitle        = $authorname;
        $metadescription = $_G['jameson_read']['seodescr'];
        $metakeywords    = $_G['jameson_read']['seokeywords'];
        $_G['setting']['seohead'] .= '<meta name="renderer"content="webkit" />';
        include template("diy:zuozhe", 0, './source/plugin/jameson_read/template/' . $_G['jameson_read']['template']);
    }
    public function book()
    {
        global $_G;
        $book_id = intval($_GET['book_id']);
        if (checkmobile()) {
            dheader('location:' . $_G['siteurl'] . mbreurl('book', $book_id));
        }
        $books = C::t('#jameson_read#jamesonread_books')->fetchAllInfoById($book_id, $_G['uid']);
        if (!$books) {
            showmessage(lang('plugin/jameson_read', 'tushubucunzai'));
        }
        if (!$books['status']) {
            showmessage(lang('plugin/jameson_read', 'gaishuyixiajia'));
        }
        $books['dashang']   = (int) DB::result_first('SELECT count(*) FROM %t WHERE book_id=%d', array('jamesonread_dashang', $books['book_id']));
        $books['dspaihang'] = C::t('#jameson_read#jamesonread_dashang')->fetch_paihang($books['book_id'], 10);
        $books['hasbuy']    = C::t('#jameson_read#jamesonread_buybooks')->hasBuyBook($_G['uid'], $books['book_id']);
        if (trim($books['shuxing'])) {
            $books['shuxing'] = explode('|', trim($books['shuxing']));
        }
        // 获取作者信息
        if ($authors_booknum = C::t('#jameson_read#jamesonread_books')->count_by_author($books['author'])) {
            $authors = C::t('#jameson_read#jamesonread_books')->fetch_by_author($books['author'], 0, 6);
        }
        $piaoinfo        = DB::fetch_all('SELECT * FROM %t WHERE ' . DB::field('type', array(101, 102, 103), 'in'), array('jamesonread_topics'), 'type');
        $categorys   = $this->_tuijian();
        $books['parent_name'] = $categorys[$books['parent_id']]['category_name'];
        $nobbname        = true;
        $navtitle        = preg_replace(array('/\[fufenlei\]/i', '/\[zifenlei\]/i', '/\[shuming\]/i', '/\[zhanming\]/i'), array($books['parent_name'], $books['category_name'], $books['book_name'], $_G['setting']['bbname']), C::t('common_setting')->fetch('xf512seo_book'));
        $metadescription = $books['book_name'] . ',' . $books['desco'] . $_G['jameson_read']['seodescr'];
        $metakeywords    = $books['book_name'] . ',' . $_G['jameson_read']['seokeywords'] . ',';
        $_G['setting']['seohead'] .= '<meta name="renderer"content="webkit" />';
        if ($_G['jameson_read']['enableshuping']) {
            $hotshuping = C::t('#jameson_read#jamesonread_dianping')->fetch_hot($book_id);
            $newshuping = C::t('#jameson_read#jamesonread_dianping')->fetch_new($book_id);
        } else {
            $hotshuping = $newshuping = array();
        }
        $hasfavore   = C::t('#jameson_read#jamesonread_favores')->hasFavore($_G['uid'], $book_id);
        $paihangbang = $this->_paihang();

        // 最新章节
        $newcolums = C::t('#jameson_read#jamesonread_colums')->fetch_newcolum_bybid($book_id);
        if ($newcolums[0]) {
            $newcolums[0]['message'] = nl2br(cutstr(strip_tags(preg_replace(array('/\[attach\].*?\[\/attach\]/ism', "/\[\w+[^\]]*\]/ism", "/\[\/\w+\]/ism", "/[^\w_=\/]jameson_read/ism"), array('', '', "", ""), $newcolums[0]['message'])), 200));
            $newcolums[0]['message'] = preg_replace('/(<br\s*\/?>\s*){2,}/ism', '<br>', $newcolums[0]['message']);
        }
        $adv = C::t('#jameson_read#jamesonread_topics')->fetch_pc_adv(3, 4);
        // 只有在显示绑定区域情况下才查询
        if ($books['bindfid']) {
            $bindforuminfo = C::t('forum_forum')->fetch_info_by_fid($books['bindfid']);
            $threadlist    = C::t('forum_thread')->fetch_all_by_fid_typeid_displayorder($books['bindfid'], null, null, '=', 0, 20);
        }
        if ($books['qzfid']) {
            $qzinfo = C::t('forum_forum')->fetch_info_by_fid($books['qzfid']);
            $qzlist = C::t('forum_thread')->fetch_all_by_fid_typeid_displayorder($books['qzfid'], null, null, '=', 0, 20);
        }
        // 如果是pdf图书
        if ($books['is_pdf']) {
            $pdfs = array();
            $pdfs = C::t('#jameson_read#jamesonread_pdf')->fetch_by_bid($book_id);
            C::t('#jameson_read#jamesonread_books')->addviews($book_id);
        }
        $fenshu = $books['dpcount'] ? round($books['scores'] / ($books['dpcount'] ? $books['dpcount'] : 1), 1) : 0;
        if ($_G['uid']) {
            $dquid = C::t('common_member_count')->fetch($_G['uid']);
        } else {
            $dquid = array();
        }
        // 判断阅读权限
        $isread = array(
            'is'  => (!$books['bookmoney'] || ($_G['uid'] == $books['uid'])) ? 1 : 0,
            'vip' => (in_array($_G['groupid'], $_G['jameson_read']['vipgroup'])) ? 1 : 0,
            'has' => $books['hasbuy'] ? 1 : 0,
        );
        $isread['showbuy'] = !$books['is_pdf'] && !$books['hasbuy'] && !$isread['vip'] && ($books['uid'] != $_G['uid']) ? 1 : 0;
        $isread['buytids'] = C::t('#jameson_read#jamesonread_buytids')->fetch_by_book_uid($_G['uid'], $books['book_id']);
        $likesame          = C::t('#jameson_read#jamesonread_books')->fetch_search($books['book_name'], 'same', 0, 7);
        $historys          = $this->history('jamesonreadbooks');
        include template("diy:index_book", 0, './source/plugin/jameson_read/template/' . $_G['jameson_read']['template']);
    }
    public function search()
    {
        global $_G;
        $keyword = dhtmlspecialchars(trim($_GET['keyword']));
        if (checkmobile()) {
            dheader("location:" . trim($_G['siteurl'], "/") . "/plugin.php?id=jameson_read&contrl=touch&act=search&keyword=" . $keyword);
        }
        if (xfxs_isutf($keyword) && strtolower(CHARSET) != 'utf-8') {
            $keyword = diconv($keyword, 'utf-8', CHARSET);
        } else if (!xfxs_isutf($keyword) && strtolower($keyword) == 'utf-8') {
            $keyword = diconv($keyword, 'GB2312', CHARSET);
        }
        $navtitle = !$keyword ? lang('plugin/jameson_read', 'sousuotushu') : $keyword . lang('plugin/jameson_read', 'sousuojieguo');
        $_G['setting']['seohead'] .= '<meta name="renderer"content="webkit" />';
        if ($keyword) {
            $currentpage = $_GET['page'] ? intval($_GET['page']) : 1;
            if (!isset($_GET['page'])) {
                C::t('#jameson_read#jamesonread_search')->addkeyword($keyword);
            }
            $counts = C::t('#jameson_read#jamesonread_books')->count_search($keyword);
            if ($counts) {
                $books    = C::t('#jameson_read#jamesonread_books')->fetch_search($keyword, $type, ($currentpage - 1) * 30, 30);
                $pageshow = multi($counts, 30, $currentpage, './plugin.php?id=jameson_read&contrl=index&act=search&keyword=' . $keyword);
            }
        } else {
            $books = C::t('#jameson_read#jamesonread_books')->fetchAll_by_field(array('is_jingxuan', '=', '1'), array(), array(' addtime desc '), 0, 30);
        }
        $adv             = C::t('#jameson_read#jamesonread_topics')->fetch_pc_adv(3, 4);
        $paihangbang     = $this->_paihang();
        $categorys       = $this->_tuijian();
        $metadescription = $_G['jameson_read']['seodescr'];
        $metakeywords    = $_G['jameson_read']['seokeywords'];
        include template("diy:search_index", 0, './source/plugin/jameson_read/template/' . $_G['jameson_read']['template']);
    }
    public function tag()
    {
        global $_G;
        $tag = dhtmlspecialchars(trim($_GET['tag']));
        if (checkmobile()) {
            dheader("location:" . trim($_G['siteurl'], "/") . "/plugin.php?id=jameson_read&contrl=touch&act=tag&tag=" . $tag);
        }
        if (xfxs_isutf($tag) && strtolower(CHARSET) != 'utf-8') {
            $tag = diconv($tag, 'utf-8', CHARSET);
        } else if (!xfxs_isutf($tag) && strtolower($tag) == 'utf-8') {
            $tag = diconv($tag, 'GB2312', CHARSET);
        }
        $navtitle = !$tag ? lang('plugin/jameson_read', 'sousuotushu') : $tag . lang('plugin/jameson_read', 'sousuojieguo');
        $_G['setting']['seohead'] .= '<meta name="renderer"content="webkit" />';
        if ($tag) {
            if (!isset($_GET['p'])) {
                C::t('#jameson_read#jamesonread_search')->addkeyword($tag, 'tag');
            }
            $currentpage = $_GET['page'] ? intval($_GET['page']) : 1;
            $counts      = C::t('#jameson_read#jamesonread_books')->count_search($tag, 'shuxing');
            if ($counts) {
                $books    = C::t('#jameson_read#jamesonread_books')->fetch_search($tag, 'shuxing', ($currentpage - 1) * 30, 30);
                $pageshow = multi($counts, 30, $currentpage, './plugin.php?id=jameson_read&contrl=index&act=tag&tag=' . $tag);
            }
        } else {
            $books = C::t('#jameson_read#jamesonread_books')->fetchAll_by_field(array('is_jingxuan', '=', '1'), array(), array(' addtime desc '), 0, 30);
        }
        $adv             = C::t('#jameson_read#jamesonread_topics')->fetch_pc_adv(3, 4);
        $paihangbang     = $this->_paihang();
        $categorys       = $this->_tuijian();
        $metadescription = $_G['jameson_read']['seodescr'];
        $metakeywords    = $_G['jameson_read']['seokeywords'];
        include template("diy:tag_index", 0, './source/plugin/jameson_read/template/' . $_G['jameson_read']['template']);
    }
    public function downloadpdf()
    {
        global $_G;
        $book_id = intval($_GET['book_id']);
        $pdfid   = intval($_GET['pdfid']);
        // 未登录不存在图书或用户组禁止下载
        if (!in_array($_G['groupid'], $_G['jameson_read']['downgroups'])) {
            showmessage(lang('plugin/jameson_read', 'wuquanxiazai'), '');
        }
        $pdfurl = DB::result_first('SELECT url FROM %t WHERE book_id=%d AND id=%d', array('jamesonread_pdf', $book_id, $pdfid));
        header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=" . basename($pdfurl));
        if (preg_match('/^\/\//i', $pdfurl)) {
            $url = 'http:' . $pdfurl;
        }
        echo file_get_contents($pdfurl);
    }

    public function download()
    {
        global $_G;
        $book_id = intval($_GET['book_id']);
        // 未登录不存在图书或用户组禁止下载
        if (!in_array($_G['groupid'], $_G['jameson_read']['downgroups'])) {
            showmessage(lang('plugin/jameson_read', 'wuquanxiazai', ''));
        }
        // 如果当前图书不存在售价则可免费下载
        $bookinfo = C::t('#jameson_read#jamesonread_books')->fetch($book_id);
        if ($bookinfo['is_pdf'] > 0) {
            showmessage(lang('plugin/jameson_read', 'xiazaichucuo', ''));
        }
        $tmpfile = "******" . $_G['setting']['bbname'] . "(" . $_G['siteurl'] . ")******\r\n<<" . $bookinfo['book_name'] . '>>  [' . $bookinfo['author'] . "]\r\n";
        // 所有章节
        $allcolums = DB::fetch_all('SELECT pid,subject,tid FROM %t WHERE book_id=%d ORDER BY zhangjie', array('jamesonread_colums', $book_id));
        // 处理messag
        foreach ($allcolums as $key => $value) {
            $message = C::t("forum_post")->fetch('tid:' . $value['tid'], $value['pid']);
            $message = $message['message'];
            $tmp     = preg_replace(array(
                "/\[.*\]\d+[\/.*]/ism", "/\[.*\]/ism", "/jameson_read/ism", "/\s{5,20}/ism", "/<br[^>]*>/ism", "/&#\d+;/ism",
            ), array('', '', '', "\r\n", "\r\n", ''), $message);
            $tmpfile .= "\r\n" . trim($value['subject']) . "\r\n";
            $tmpfile .= "\r\n" . trim(strip_tags($tmp)) . "\r\n";
        }
        header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=" . preg_replace(array("/[\?\*\{\}\<\>&;\+\/\\\\]/"), array(''), $bookinfo['book_name']) . '.txt');
        echo $tmpfile;
    }
// 福利页面
    public function fuli()
    {
        global $_G;
        $fulitext = DB::fetch_first('SELECT topic_id,adv,type FROM %t WHERE type=%d', array('jamesonread_topics', 38));
        include './source/function/function_discuzcode.php';
        $fulitext['adv'] = nl2br(discuzcode(stripcslashes($fulitext['adv']), 0, 0, 1, 1, 1, 1, 1));
        $paihangbang     = $this->_paihang();
        $categorys       = $this->_tuijian();
        $navtitle        = lang('plugin/jameson_read', 'zuozhefuli');
        $metadescription = $_G['jameson_read']['seodescr'];
        $metakeywords    = $_G['jameson_read']['seokeywords'];
        $adv             = C::t('#jameson_read#jamesonread_topics')->fetch_pc_adv(3, 4);
        $_G['setting']['seohead'] .= '<meta name="renderer"content="webkit" />';
        include template("diy:index_fuli", 0, './source/plugin/jameson_read/template/' . $_G['jameson_read']['template']);
    }
// 当前申请状态
    public function shenqing()
    {
        global $_G;
        if (!$_G['uid']) {
            showmessage(lang('plugin/jameson_read', 'qingxiandenglu'), 'member.php?mod=logging&action=login', 'error');
        }
        if (FORMHASH == $_GET['formhash']) {
            $data             = array();
            $data['xingming'] = daddslashes(trim($_GET['xingming']));
            $data['lianxi']   = daddslashes(trim($_GET['lianxi']));
            $data['fuyan']    = daddslashes(trim($_GET['fuyan']));
            $data['author']   = daddslashes(trim($_G['username']));
            $data['uid']      = $_G['uid'];
            $data['groupid']  = $_G['groupid'];
            $data['addtime']  = TIMESTAMP;
            C::t('#jameson_read#jamesonread_shenhe')->insert($data);
            showmessage(lang('plugin/jameson_read', 'yitijiao'), dreferer(), 'succeed');
        } else {
            if (checkmobile()) {
                dheader('location:' . $_G['siteurl'] . mbreurl('shenqing'));
            }
            // 是否已有申请
            $hasdata         = DB::fetch_first('SELECT * FROM %t WHERE uid=%d', array('jamesonread_shenhe', $_G['uid']));
            $paihangbang     = $this->_paihang();
            $categorys       = $this->_tuijian();
            $navtitle        = lang('plugin/jameson_read', 'shenqingzuozhe');
            $adv             = C::t('#jameson_read#jamesonread_topics')->fetch_pc_adv(3, 4);
            $metadescription = $_G['jameson_read']['seodescr'];
            $metakeywords    = $_G['jameson_read']['seokeywords'];
            $_G['setting']['seohead'] .= '<meta name="renderer"content="webkit" />';
            include template("diy:index_shenqing", 0, './source/plugin/jameson_read/template/' . $_G['jameson_read']['template']);
        }
    }
    public function bookstore()
    {
        global $_G;
        if (checkmobile()) {
            dheader('location:' . $_G['siteurl'] . mbreurl('store'));
        }
        if (!$_G['uid']) {
            showmessage(lang('plugin/jameson_read', 'bixudenglu'), null, array(), array('showmsg' => true, 'login' => 1));
        }
        $currentpage = $_GET['page'] ? intval($_GET['page']) : 1;
        $type        = $_GET['type'] ? $_GET['type'] : 'fav';
        $pagesize    = 50;
        switch ($type) {
            case 'fav':
                $counts = C::t('#jameson_read#jamesonread_favores')->count_by_uid($_G['uid']);
                $books  = C::t('#jameson_read#jamesonread_favores')->fetch_by_page($_G['uid'], ($currentpage - 1) * $pagesize, $pagesize);
                $cururl = './plugin.php?id=jameson_read&contrl=index&act=bookstore&type=fav';
                break;
            case 'fx':
                $counts  = C::t('#jameson_read#jamesonread_fx')->count_byuid($_G['uid']);
                $booksfx = C::t('#jameson_read#jamesonread_fx')->fetch_byuid($_G['uid'], ($currentpage - 1) * $pagesize, $pagesize);
                $cururl  = './plugin.php?id=jameson_read&contrl=index&act=bookstore&type=fx';
                break;
            case 'ds':
                $counts  = C::t('#jameson_read#jamesonread_dashang')->count_by_uid($_G['uid']);
                $booksds = C::t('#jameson_read#jamesonread_dashang')->fetch_by_uid($_G['uid'], ($currentpage - 1) * $pagesize, $pagesize);
                $cururl  = './plugin.php?id=jameson_read&contrl=index&act=bookstore&type=ds';
                break;
            case 'buy':
                $counts      = C::t('#jameson_read#jamesonread_buytids')->count_by_uid($_G['uid']);
                $booksbuytid = C::t('#jameson_read#jamesonread_buytids')->fetch_by_page($_G['uid'], ($currentpage - 1) * $pagesize, $pagesize);
                $cururl      = './plugin.php?id=jameson_read&contrl=index&act=bookstore&type=buy';
                if (count($booksbuytid) < $pagesize) {
                    $booksbuybook = C::t('#jameson_read#jamesonread_buybooks')->fetch_by_page($_G['uid'], 0, 0);
                }
                break;
            case 'sp':
                $counts   = C::t('#jameson_read#jamesonread_piao')->count_by_uid($_G['uid']);
                $shupiaos = C::t('#jameson_read#jamesonread_piao')->fetch_by_page($_G['uid'], ($currentpage - 1) * $pagesize, $pagesize);
                $cururl   = './plugin.php?id=jameson_read&contrl=index&act=bookstore&type=sp';
                break;
            case 'sq':
                $counts  = C::t('#jameson_read#jamesonread_bookmarks')->count_by_uid($_G['uid']);
                $bookssq = C::t('#jameson_read#jamesonread_bookmarks')->fetch_by_uid($_G['uid'], $pagesize, ($currentpage - 1) * $pagesize);
                $cururl  = './plugin.php?id=jameson_read&contrl=index&act=bookstore&type=s1';
                break;
        }
        $pageshow        = multi($counts, $pagesize, $currentpage, $cururl);
        $adv             = C::t('#jameson_read#jamesonread_topics')->fetch_pc_adv(3, 4);
        $paihangbang     = $this->_paihang();
        $categorys       = $this->_tuijian();
        $navtitle        = lang('plugin/jameson_read', 'wodeshujia');
        $metadescription = $_G['jameson_read']['seodescr'];
        $metakeywords    = $_G['jameson_read']['seokeywords'];
        $_G['setting']['seohead'] .= '<meta name="renderer"content="webkit" />';
        include template("diy:bookstore", 0, './source/plugin/jameson_read/template/' . $_G['jameson_read']['template']);
    }
    public function read()
    {
        global $_G;
        $columinfo = C::t('#jameson_read#jamesonread_colums')->fetch_colum_bytid($_GET['tid']); //获取章节信息
        if (checkmobile()) {
            dheader('location:' . $_G['siteurl'] .'plugin.php?id=jameson_read&contrl=touch&act=read&tid='.$columinfo['tid'].'&pid='.$columinfo['pid'].'&fxuid='.intval($_GET['fxuid']).'&highlight='.$_GET['highlight']);
            exit;
        }
        !$columinfo && showmessage(lang('plugin/jameson_read', 'zhangjiebucunzaihuoyishanchu'), '', 'error');
        // 如果审核中
        if (DB::result_first('SELECT count(*) FROM %t WHERE id=%d', array('forum_thread_moderate', $_GET['tid']))) {
            $backurl = dreferer();
            // 如果来源是发帖页面，则跳转到作者中心
            if (preg_match("/mod=post/i", $backurl)) {
                $backurl = './plugin.php?id=jameson_read&contrl=author&act=book&book_id=' . $columinfo['book_id'] . '&forward=book_column';
            }
            showmessage(lang('plugin/jameson_read', 'shenhezhong'), $backurl);
        }
        // 图书信息
        $bookinfo = C::t('#jameson_read#jamesonread_books')->fetchAllInfoById($columinfo['book_id']);
        // 如果本书具有售价则判断是否购买了本书
        if ($columinfo['price'] && C::t('#jameson_read#jamesonread_buybooks')->hasBuyBook($_G['uid'], $bookinfo['book_id'])) {
            $shifougoumaibutton = 1;
        } else {
            $shifougoumaibutton = 0;
        }
        // 是否购买了本章节
        if (!$columinfo['price'] || ($columinfo['uid'] == $_G['uid']) || in_array($_G['groupid'], $_G['jameson_read']['vipgroup']) || C::t('#jameson_read#jamesonread_buytids')->hasBuyTid($_G['uid'], $columinfo['tid'])) {
            $shifougoumaizhangjie = 1;
        } else {
            $shifougoumaizhangjie = 0;
        }
        if ($shifougoumaibutton < 1 && $shifougoumaizhangjie < 1) {
            // 进入这里，本章节需要购买才可阅读
            if (getcookie('jamesonreadautobuy_' . $_G['uid'])) {
                // 如果设置了自动购买，则自动扣费，否则显示购买按钮
                if ($this->autobuy($columinfo)) {
                    $shifougoumaizhangjie = 1;
                }
            }
        }
        if (($_G['jameson_read']['mustlogin'] && !$_G['uid']) || ($shifougoumaibutton < 1 && $shifougoumaizhangjie < 1)) {
            // 如果没有购买过，则进行提示购买操作
            // 首先获取本章节的前200个文字
            $message = C::t("forum_post")->fetch('tid:' . $columinfo['tid'], $columinfo['pid'], true);
            $message = cutstr($message['message'], 500, '');
            $message = preg_replace(array('/\[attach\].*?\[\/attach\]/ism', "/\[\w+[^\]]\]/ism", "/\[\/\w+\]/ism", "/[^=_\w\/]jameson_read/ism"), array('', '', "", ""), $message);
            $message = cutstr(trim(strip_tags($message)), 200);
            if ($shifougoumaibutton < 1 && $shifougoumaizhangjie < 1) {
                $shifoukedu = 0;
                $message .= '<strong class="xs3 marlm rq">'
                . lang('plugin/jameson_read', 'goumaibenzhangjiejixu')
                    . '</strong>';
            } else {
                $shifoukedu = 1;
                $message .= '<a href="javascript:;" onclick="showWindow(\'login\', \'member.php?mod=logging&action=login&referer=\'+encodeURIComponent(location.href))" class="xs3 marlm rq">'
                . lang('plugin/jameson_read', 'dengluhouyueduwanzheng')
                    . '</a>';
            }
        } else {
            $shifoukedu      = 1;
            $nodisplayauthor = 0;
            $message         = C::t("forum_post")->fetch('tid:' . $columinfo['tid'], $columinfo['pid'], true);
            if (preg_match("/jameson_read$/", $message['message'])) {
                include_once './source/function/function_discuzcode.php';
                $_G['forum_attachpids'][] = $columinfo['pid'];
                if (preg_match_all("/\[attach\](\d+)\[\/attach\]/ism", $message['message'], $matchaids)) {
                    $_G['forum_attachtags'][$columinfo['pid']] = $matchaids[1];
                }
                $tupianfujian = array();
                $_G['tid']    = $columinfo['tid'];
                require_once libfile('function/attachment');
                parseattach($_G['forum_attachpids'], $_G['forum_attachtags'], $tupianfujian);
                if ($tupianfujian[$columinfo['pid']]['attachments']) {
                    foreach ($tupianfujian[$columinfo['pid']]['attachments'] as $key => $value) {
                        if (in_array(strtolower($value['ext']), array('jpg', 'png', 'gif'))) {
                            $img = '<img src="'
                                . $value['url']
                                . $value['attachment']
                                . '" />';
                            $patt = "/\[attach\]("
                                . $key
                                . ")\[\/attach\]/ism";
                            $message['message'] = preg_replace($patt, $img, $message['message']);
                        }
                    }
                }
                $message['message'] = preg_replace(array("/\[audio\](.*?)\[\/audio\]/", "|\[img=?(\d+)?,?(\d+)?\](.*?)\[/img\]|"), array('<audio src="$1"  controls="controls"></audio>', '<img src="$3" width="$1" height="$2">'), $message['message']);

                // 原始解析后
                $codemessage = discuzcode($message['message'], 0, 0, 1, 1, 1, 1, 1, 0, '0', $columinfo['uid'], '0');
                $message     = preg_replace(array(
                    "/[^=_\/]jameson_read/ism",
                    "/\[code\](.*?)\[\/code\]/ism",
                    "/\[quote\]/i",
                    "/\[\/quote\]/i",
                    "/&#\d+;/",
                ),
                    array(
                        '',
                        '######',
                        '<blockquote>',
                        '</blockquote>',
                        '',
                    ), $codemessage);

                preg_match_all('/\[code\](.*?)\[\/code\]/ism', $codemessage, $codehtml);
                // 存在源代码格式
                if ($codehtml) {
                    $codearray = array();
                    foreach ($codehtml[1] as $key => $value) {
                        $tmp = '<pre><code>'
                        . dhtmlspecialchars($value)
                            . '</code></pre>';
                        $message = preg_replace('/######/', $tmp, $message);
                    }
                }
                // cuplayer视频解析
                if (preg_match("/\[cuplayer\](.*)\[\/cuplayer\]/", $message, $cuplayer)) {
                    $message = preg_replace("/\[cuplayer\](.*)\[\/cuplayer\]/", '<video  src="{$cuplayer[1]}" width="100%" controls preload></video>', $message);
                }
                if (!preg_match("/<(p|div)[^>]*?>/ism", $message)) {
                    $message = '<p>' . preg_replace(array(
                        "/\n/s",
                        "/<br\s*?\/?>/si",
                    ), array(
                        "</p><p>",
                        "</p><p>",
                    ), $message) . '</p>';
                }
                $message = preg_replace(array(
                    "/<p\s*?>\s*?<br\s*\/?>/ism",
                ), array(
                    "<p>",
                ), $message);
                $message = stripcslashes($message);
            } else {
                $aftermessage = preg_replace(
                    array(
                        "/<code>(.*?)<\/code>/ism",
                    ),
                    array(
                        '######',
                    ), $message['message']);
                $aftermessage = preg_replace(
                    array(
                        "/(<\w+[^>]*?\s)on(\w+)/ism",
                    ),
                    array(
                        '\1 \2',
                    ), $aftermessage);
                preg_match_all('/<code>(.*?)<\/code>/ism', $message['message'], $codehtml2);
                // 存在源代码格式
                if ($codehtml2) {
                    $codearray = array();
                    foreach ($codehtml2[1] as $key => $value) {
                        $tmp = '<code>'
                        . preg_replace(array('/</', '/>/'), array('&lt;', '&gt;'), $value)
                            . '</code>';
                        $aftermessage = preg_replace('/######/', $tmp, $aftermessage, 1);
                    }
                }
                $message = stripcslashes($aftermessage);
            }
            $subject = $columinfo['subject'];
            if(isset($_GET['highlight']) && $_GET['highlight']){
                require_once libfile('function/search');
                $subject = bat_highlight($columinfo['subject'],$_GET['highlight']);
                $message = bat_highlight($message,$_GET['highlight']);
            }
            if ($_G['uid'] && ($_GET['fxuid'] > 0) && !in_array($_G['uid'], array($_GET['fxuid'], $columinfo['uid']))) {
                // 分享奖励积分
                $this->fxact($_GET['fxuid'], $columinfo['tid'], $columinfo['book_id'], $_G['jameson_read']['jiangli'], $_G['jameson_read']['fxtrameid'], $_G['clientip']);
            }
            // 添加阅读量数据
            C::t('#jameson_read#jamesonread_books')->addviews($columinfo['book_id']);
            // 插入阅读历史记录
            if ($history = getcookie('jamesonreadbooks')) {
                $history     = unserialize($history);
                $hisflag     = false;
                $lasthasread = '';
                foreach ($history as $key => $value) {
                    $tmp = explode(',', $value);
                    if ($tmp[0] == $columinfo['book_id']) {
                        if ($hisflag) {
                            unset($history[$key]);
                            continue;
                        }
                        // 存在相同book_id更新
                        if ($tmp[1] != $columinfo['tid']) {
                            $history[$key] = $columinfo['book_id']
                                . ','
                                . $columinfo['tid']
                                . ','
                                . $columinfo['pid']
                                . ','
                                . $columinfo['subject']
                                . ','
                                . $bookinfo['book_name']
                                . ','
                                . $bookinfo['image'];
                            $lasthasread = $value;
                        }
                        $hisflag = true;
                    }
                }
                if (!$hisflag) {
                    $history[] = $columinfo['book_id']
                        . ','
                        . $columinfo['tid']
                        . ','
                        . $columinfo['pid']
                        . ','
                        . $columinfo['subject']
                        . ','
                        . $bookinfo['book_name']
                        . ','
                        . $bookinfo['image'];
                }
            } else {
                $history = array($columinfo['book_id']
                    . ','
                    . $columinfo['tid']
                    . ','
                    . $columinfo['pid']
                    . ','
                    . $columinfo['subject']
                    . ','
                    . $bookinfo['book_name']
                    . ','
                    . $bookinfo['image']);
            }
            dsetcookie('jamesonreadbooks', serialize($history), 48 * 3600);
        }

        $piaoinfo = DB::fetch_all('SELECT * FROM %t WHERE ' . DB::field('type', array(101, 102, 103), 'in'), array('jamesonread_topics'), 'type');
        if ($_G['uid']) {
            $dquid = C::t('common_member_count')->fetch($_G['uid']);
        } else {
            $dquid = array();
        }
        // 上一章数据
        $predata = C::t('#jameson_read#jamesonread_colums')->precolum($columinfo['book_id'], $columinfo['zhangjie'], $columinfo['colum_id']);
        // 下一章数据
        $nextdata = C::t('#jameson_read#jamesonread_colums')->nextcolum($columinfo['book_id'], $columinfo['zhangjie'], $columinfo['colum_id']);
        // adv
        if ($_G['jameson_read']['pcyuedugg']) {
            $pcyuedugg = C::t('#jameson_read#jamesonread_topics')->fetch_by_type(7);
        }
        // 本书是否在书架
        $hasfavore = C::t('#jameson_read#jamesonread_favores')->hasFavore($_G['uid'], $columinfo['book_id']);
        // 本章节是否已加入书签
        $hasmark = !$_G['uid'] ? 0 : C::t('#jameson_read#jamesonread_bookmarks')->hasMark($columinfo['tid'], $_G['uid']);
        // 本书的所有书签信息
        $marks = C::t('#jameson_read#jamesonread_bookmarks')->fetch_bybid($_G['uid'], $columinfo['book_id']);
        // 取得本书的书评信息
        $shuping = C::t('#jameson_read#jamesonread_dianping')->fetch_hot($columinfo['book_id']);
        // 评分
        $scores = round($bookinfo['scores'] / $bookinfo['dpcount'], 1);
        // 图书封面图片处理
        $image = $_G['jameson_read']['morenfengmian'];
        if ($bookinfo['image'] && preg_match('/^http|\/\//i', $bookinfo['image'])) {
            $image = $bookinfo['image'];
        } else if ($bookinfo['image']) {
            $image = './data/attachment/forum/' . $bookinfo['image'];
        }
        $bookinfo['parent_name'] = C::t('#jameson_read#jamesonread_categorys')->fetch_name($bookinfo['parent_id']);
        $nobbname = true;
        $navtitle = preg_replace(array('/\[fufenlei\]/i', '/\[zifenlei\]/i', '/\[zhangjie\]/i', '/\[shuming\]/i', '/\[zhanming\]/i'), array($bookinfo['parent_name'], $bookinfo['category_name'], $columinfo['subject'], $bookinfo['book_name'], $_G['setting']['bbname']), C::t('common_setting')->fetch('xf512seo_read'));
        $_G['setting']['seohead'] .= '<meta name="renderer"content="webkit" />';
        $autobuycookie = 0;
        if ($_G['uid'] && getcookie('jamesonreadautobuy_' . $_G['uid'])) {
            $autobuycookie = 1;
        }
        $metadescription = $columinfo['subject'] . ',' . $bookinfo['book_name'] . ',' . $bookinfo['desco'] . $_G['jameson_read']['seodescr'];
        $metakeywords    = $columinfo['subject'] . ',' . $bookinfo['book_name'] . ',' . $_G['jameson_read']['seokeywords'] . ',';
        include template("diy:read" . ($_G['jameson_read']['simpleread'] == 4 ? 3 : $_G['jameson_read']['simpleread']) . "_index", 0, './source/plugin/jameson_read/template');
    }
}
